Skip to content

feat: run AWS CLI commands with the official AWS CLI v2 through lstk aws - #137

Draft
joe4dev wants to merge 15 commits into
mainfrom
devx-1330-mcp-server-run-aws-cli-commands-with-the-official
Draft

joe4dev wants to merge 15 commits into
mainfrom
devx-1330-mcp-server-run-aws-cli-commands-with-the-official

Conversation

@joe4dev

@joe4dev joe4dev commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Linear: DEVX-1330 · related: DEVX-1331 (lstk fix this PR works around)

Summary

localstack-aws-client and the deployer's create-stack/delete-stack ran awslocal inside the LocalStack container. They now run the official AWS CLI v2 through lstk aws where the server runs: on the user's machine with npx, or in the server's Docker image. The deployer already runs Terraform, CDK and SAM through lstk the same way.

awslocal is AWS CLI v1 (1.46.3) that the LocalStack image happens to install, and the image's Dockerfile has a TODO to remove it.

 src/tools/localstack-aws-client.ts, src/tools/localstack-deployer.ts
-  docker exec <localstack> awslocal …
+  runLstkAws(…)                        src/lib/aws/lstk-aws.ts
 src/lib/aws/child-env.ts               (new) allow-listed env, private HOME
 src/lib/azure/egress-guard.ts          relayHttp: plain HTTP to LocalStack only
 src/lib/aws/local-paths.ts             (new) LOCALSTACK_AWS_WORKDIR and the path rule
 src/lib/aws/aws-cli-sanitizer.ts       argv checks and the deny list
 Dockerfile                             FROM amazon/aws-cli (trimmed), mandoc

Decision: confine the CLI with rules (option B)

Inside the LocalStack container, awslocal could not see the user's files, AWS credentials, ~/.aws config or programs. Run where the server runs, the CLI can. So an agent's command could, without these rules, reach real AWS with real credentials, read ~/.aws/credentials, overwrite ~/.zshrc, or start ssh.

We chose to keep the CLI where the server runs and confine it with a minimal set of rules, accepting that the rules on files and commands are a model of the CLI's behavior rather than a hard boundary.

A. Throwaway container per command B. Rules (chosen) C. Allow-list API operations
How Run lstk aws in a container that mounts only the workdir, read-only root, no docker.sock, network only to LocalStack Allow-listed env + private HOME + egress guard, plus path rule and deny list Allow modeled API operations and a vetted few customizations (s3 ls/cp/mv/rm/sync/mb/rb/presign); local files only through file:// and outfiles
Pros A real boundary, like awslocal had; files and programs confined without modeling the CLI No extra image or container start; works in npx and Docker mode as is; small code Smaller surface to reason about than a deny list
Cons ~0.5–1 s per command; needs a small linux image with lstk + aws to publish and pull; more moving parts in npx mode File and command rules model the CLI: rounds 1–10 and 12 each found gaps in them (round 11 none), so expect more Drops less common commands; still models CLI parsing (abbreviations, $VARS, shorthand)

The network side is structural and has held since review round 4. Rounds 7–10 still found file-rule gaps each time (variables the CLI expands, glob anchoring of s3 filters, .git as a file, Unicode name folding), round 11 found none, and round 12 found Windows drive paths written as C:// (fixed). The private HOME and env mean the CLI never sees real credentials or the user's AWS config, and the egress guard refuses every host but LocalStack, whatever route the CLI takes.

The rules

  1. Environment (child-env.ts). Built from an allow-list. HOME is private, so there's no user ~/.aws: no profiles, credential_process, plugins, aliases or history. AWS_* and LSTK_* are dropped. The endpoint, test credentials and region are pinned, AWS_IGNORE_CONFIGURED_ENDPOINT_URLS=false, and Multi-Region Access Points are off.
  2. Egress guard (egress-guard.ts, shared with the Azure tool). Every request goes through it as the HTTP(S) proxy. It relays plain HTTP to the LocalStack host and its subdomains on the LocalStack port, and refuses every other host. A refusal fails the tool call.
    • LocalStack is deliberately not in NO_PROXY: botocore picks a client's proxy from its configured endpoint, so a request rewritten to another host would bypass the guard.
  3. Command checks (aws-cli-sanitizer.ts, on the parsed argv).
    • The existing checks: no shell syntax and no ...
    • No --endpoint-url/--profile or their abbreviations, and no lstk --config.
    • help only as the end of a pure help request (lstk bug, DEVX-1331).
    • A deny list of commands that act on the machine: update, login/signup/sso login, ssh/sessions/tunnels, codeartifact login, eks update-kubeconfig, cloudformation package, deploy push, gamelift upload-build, gamelift get-game-session-log (the only command that fetches a URL from a server response, with urlopen, which opens file:// too), lambda-web, lightsail push-container-image, history, cli-dev, and the endless log streams (logs tail --follow, logs start-live-tail). Other long-running commands end at the 5-minute timeout.
  4. Local files (local-paths.ts). The CLI runs in LOCALSTACK_AWS_WORKDIR. It defaults to the server's directory, with none in the Docker image or when the server runs in / or the home directory. Every value is judged by its shape, not its option name, because the CLI accepts abbreviated option names:
    • Relative values must resolve, symlinks followed, inside that directory.
    • Absolute and ~ values must be inside the workdir, unless they are a name the CLI can't read or write: their first directory doesn't exist, or, outside s3 transfers, neither the path nor its parent exists (/aws/lambda/f, /dev/db/password). ~ is checked as both the real and the private home.
    • Only URLs with a lower-case scheme of two or more letters (s3://, https://) are not paths: C://Users/x is a Windows drive path.
    • file:// values and shorthand @= loads are always paths.
    • No variable references ($VAR, ${VAR}, %VAR%) in a path: the CLI expands them with an environment the server can't know (lstk and the CLI's launcher add their own, such as _PYI_ARCHIVE_FILE). Inline documents (starting with { or [, or multi-line) are exempt, so ${AWS::Region} and $states keep working.
    • Nothing inside .git or .lstk, compared as a case-insensitive file system folds names, because git and lstk run what their config says.
    • s3 cp/mv/sync write the bucket's keys as local paths. They get --no-follow-symlinks (needs AWS CLI ≥ 2.37.7) and --exclude filters for .git and .lstk, both last, because the last flag and filter win. No glob characters outside filter patterns, in the arguments or in the working directory's path, because the CLI anchors filters at the transfer's root.

Evidence

  • yarn test: 670 passed (1 Windows-only test skipped), including:
    • Tool tests against a fake lstk/aws.
    • A fake lstk that reads stdin and sends requests through the guard. It shows the private HOME, the dropped AWS_PROFILE/AWS_ENDPOINT_URL_S3/LSTK_ENDPOINT_URL, relays to LocalStack subdomains with the Host header kept, and a blocked s3.amazonaws.com.
    • Path-rule and sanitizer cases for every bypass found in review (round 7's and round 12's were checked to fail against the previous rule).
    • Main's handler tests (fix: run awslocal against the gateway's container-side address #138), ported to lstk aws: no auth token or LocalStack not running runs nothing, and the auth token reaches neither the CLI, the response nor analytics.
  • End to end against a fake LocalStack and fake S3, with the real CLIs:
    • On the host with lstk 1.5.0 and aws 2.41.1/2.42.1: every exploit from the review rounds is refused and everyday commands work (including s3 sync/cp --recursive, which skip .git and .lstk).
    • In the image built from this branch (aws-cli/2.39.3, lstk 1.4.4), against a real LocalStack: create-stack/delete-stack with a mounted template, s3 mb/presign, refusals of /etc/passwd, $_PYI_ARCHIVE_FILE and --endpoint-url, and help rendering.
  • New live tests in tests/mcp/tools.spec.mjs:
    • The AWS client reaches LocalStack through lstk aws. With MCP_TEST_RESTART_LOCALSTACK=1, which CI sets, the test first stops LocalStack and has the server start it; without it, a local run leaves the developer's instance alone.
    • The deployer creates and deletes a CloudFormation stack.
    • The AWS client refuses MRAP, endpoint and path escapes and update.
    • tests/mcp/aws-client-ports.spec.mjs (from fix: run awslocal against the gateway's container-side address #138): remapped and moved gateway ports, presigned URLs from the host.
    • Run locally against LocalStack on port 4611: 19/19 passed; the AWS client test again with and without MCP_TEST_RESTART_LOCALSTACK.
  • tests/docker/validate-image.mjs against the image built from this branch, with CI's skips (cloudpods,ephemeral,replicator,chaos) and LocalStack on port 4612: 16/16 passed. It now also presigns a URL through the image and fetches it from the host.
  • tsc --noEmit clean.

Merge Danger

Door: two-way

Blast Radius: every AWS CLI call an agent makes through the server, and the image size

  • The AWS CLI now runs on the user's machine (npx) or in the server container, confined by the rules above instead of by the LocalStack container. The file and command rules are best effort (see the decision).
  • npx users need lstk and AWS CLI ≥ 2.37.7 on the PATH.
  • Local files must be in LOCALSTACK_AWS_WORKDIR, which defaults to the server's directory. In the Docker image there is none unless it's set.
  • The image grows by about 250 MB unpacked (the AWS CLI's frozen Python and service models; examples and aws_completer are trimmed). The FROM images now wait 30 days for updates, because the AWS CLI releases almost daily.
  • A LOCALSTACK_HOSTNAME that is not a DNS name or IPv4 address, or a LOCALSTACK_PORT that is not a port, now fails with a clear error (it failed with Invalid URL or named another host before).
  • Responses are unchanged, except that lstk's "No AWS profile found" note is dropped and help pages render as plain text.
  • In the Docker image, the CLI addresses LocalStack as localhost.localstack.cloud and the egress guard connects it to host.docker.internal, so presigned URLs open on the host (as awslocal's did).

TODO

  • Known and accepted: the deployer's create-stack reads templatePath from anywhere, as before this PR (the deployer works on any project directory).
  • Not run on Windows: the drive-path refusal test only runs there.

Follow-up (out of scope for this PR)

  • Pre-existing, not from this PR: the SIGKILL fallback in src/core/command-runner.ts never fires, because child.killed is already true after SIGTERM. lstk does stop aws on SIGTERM.
  • Remove the MCP rules that lstk aws takes over, once each ships (then require that lstk version):
    • DEVX-1331 help token anywhere → the help-token rule
    • DEVX-1345 --endpoint-url/--profile → the prefix check
    • DEVX-1346 Multi-Region Access Points → AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS
    • DEVX-1347 service-specific endpoints for helper clients → endpoint pinning in the child env

🤖 Generated with Claude Code

joe4dev and others added 13 commits November 20, 2026 16:00
The AWS client tool and the deployer's create-stack/delete-stack actions ran
awslocal inside the LocalStack container. They now run the official AWS CLI v2
through `lstk aws` where the server runs, like Terraform, CDK and SAM.

- Docker image: AWS CLI v2 copied from amazon/aws-cli (trimmed), Dependabot-managed
- CI host-tools action exports the same CLI
- Command checks keep every command on LocalStack (help tokens, option prefixes,
  stack names); the CLI gets no stdin
- Tool tests, plus a live create/delete-stack test

Towards DEVX-1330

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…workdir

- Run lstk aws with an allow-listed environment and a private HOME: no user
  ~/.aws (profiles, credential_process, plugins, aliases, history), no AWS_*
  or LSTK_* from the server's environment
- Route every request through the egress guard, which relays plain HTTP to
  LocalStack and refuses other hosts; disable Multi-Region Access Points
- Hold local paths (s3 cp, file://, --body, outfiles) to LOCALSTACK_AWS_WORKDIR
- Refuse commands that act on this machine (update, login, sso login,
  history, ssm start-session, codeartifact login, cloudformation package, ...)
- Render help with mandoc in the image; strip overstrike
- 30-day cooldown for the Dockerfile images; unique live-test names

Towards DEVX-1330

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Round 4 found `--file-path`, `--priv-launch-key` and `--private-key` exempt as
name options. The path rule now lists the options that take local files from
the AWS CLI v2 source (customizations and streaming blobs), checks a name-like
option's value when it names an existing file, and checks every file:// inside
a value (shorthand `key@=fileb://…`). Refuses `wizard`, `logs start-live-tail`
and `logs tail --follow`.

Towards DEVX-1330

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t global options

Round 5 found that a quoted `..` passed the raw-string traversal check and that
relative positional paths were never resolved, so `s3 cp '../x'` read and wrote
outside the workdir (and, without one, could write an alias into the private
HOME). It also found that a global option before the operation
(`cloudformation --no-cli-pager package`) shifted the deny list's word positions.

- Check `..` on the parsed argv
- Resolve every value but a name or URL, relative ones too, against the
  directory the CLI runs in, following symlinks; never allow the private HOME
- Match a denied operation at any word after the service
- Refuse lstk's own --config; add --no-follow-symlinks to s3 cp/mv/sync
- Live test: the AWS client reaches the LocalStack the server started

Towards DEVX-1330

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Round 6 found that option names prove nothing (the CLI accepts abbreviations:
`--public-key` is `--public-key-outfile`), that the CLI expands `$VARS` in
paths, and more commands that act on the machine.

- Judge every value by its shape: relative ones resolve inside the directory
  the CLI runs in; absolute and ~ ones must be inside the workdir unless their
  first directory does not exist (a name such as /aws/lambda/f); file:// is
  always a path. Drops the PATH/NAME option lists and the over-blocking of
  values such as /start or /index.html
- Refuse a leading $VAR, and / or the home directory as LOCALSTACK_AWS_WORKDIR
- Deny deploy push, gamelift upload-build, lambda-web, lightsail
  push-container-image and cli-dev; catch abbreviations of --follow
- Require AWS CLI 2.37.7+, whose downloads honor --no-follow-symlinks

Towards DEVX-1330

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#138 added handler tests for the aws-client and the deployer, and a live
test against remapped gateway ports, all for awslocal in the container.

- Both handler test files now use main's harness: analytics and the
  preflights run for real, with PostHog and the gateway health probe
  mocked; the spawned lstk/aws pair is faked through runCommand
  (shared helpers in lstk-aws-fakes.ts).
- Ported cases: no auth token or LocalStack not running runs nothing,
  the auth token reaches neither the CLI's env, the response nor
  analytics, create-stack errors and a missing stackName.
- New: the endpoint follows LOCALSTACK_PORT, so s3 presign names the
  host port.
- aws-client-ports.spec.mjs gives each case its own
  LOCALSTACK_AWS_WORKDIR and uploads a file from it instead of
  /etc/hostname, and checks presign in every case: the CLI now builds
  the URL on the host, so the default case works too.

Also restores the README edits from #119 (MAIN_CONTAINER_NAME, Using lstk)
that resolving the rebase conflict had dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…llow-symlinks

Review round 7 found two ways out of the working directory:

- The CLI expands $VAR, ${VAR} and ~ anywhere in a path, and its
  environment always holds an empty variable (AWS_PAGER). Only a leading
  $VAR was refused, so /$AWS_PAGER/Users/x passed as a name and
  .$AWS_PAGER./x as a relative path, for reads and writes. Every value
  is now also checked as the CLI expands it, with the CLI's own
  environment, and with a variable it does not hold (lstk may add some)
  tried as empty, ., / and ..; ~ is the private home there.
- An abbreviated --follow-symlinks (--follow-sym) after
  --no-follow-symlinks won. Every prefix is refused and
  --no-follow-symlinks is always appended last.

Also:
- Nothing inside .git or .lstk: git and lstk run what their config
  there says.
- Outside s3 cp/mv/sync, an absolute value is also a name when neither
  it nor its parent exists, since the CLI writes outfiles only into
  existing directories: /dev/db/password works again.
- The private dirs are removed on exit, and a new server removes those
  of processes that no longer run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…out of .git

Review round 8: lstk sets PYTHONUNBUFFERED=1 (and its own AWS_* values)
in the CLI's environment, so `dir$PYTHONUNBUFFERED/secret` expanded to a
file outside the workdir while the check, which tried unknown variables
only as "", ., / and .., took it for a name. Guessing values cannot be
sound, so values are no longer expanded for the check:

- A value may not reference a variable the child env holds, or one lstk
  may set (AWS_*, PYTHON*, LSTK_*, LOCALSTACK_*), as $VAR, ${VAR}, or
  %VAR% on Windows (names in any case there). Any other variable is not
  set and stays literal to the CLI, so ${AWS::Region}, $states and
  $input in inline documents keep working.
- The child env sets PYTHONUNBUFFERED=1 itself; lstk only sets it when
  it is missing.

Also from the round: s3 cp/mv/sync write the bucket's keys as local
paths, so a recursive download wrote .git/config and sync --delete could
remove .git. They now get --exclude filters for .git and .lstk at any
depth and in any case, after the user's filters (the last match wins).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review round 9: the CLI joins every --exclude pattern to the transfer's
root and matches with fnmatch, so a root with glob characters
(s3://b/a[x]/) kept the .git filter from matching and a recursive
download wrote .git/config. s3 cp, mv and sync now refuse *, ?, [ and ]
in every argument but --exclude and --include patterns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review round 10:

- The CLI's PyInstaller launcher adds variables of its own
  (_PYI_ARCHIVE_FILE is the CLI's path, _PYI_PARENT_PROCESS_LEVEL=1), so
  no list of names is complete. A value checked as a path may no longer
  reference any variable ($VAR, ${VAR}, %VAR% on Windows), unless it is
  an inline document (starts with { or [, or spans lines), which can only
  expand to a path inside a directory named {. $5 is no variable name. A
  file:// path never may.
- A key named exactly .git wrote a .git file (gitdir: ...), which git
  follows. The s3 filters now also exclude .git and .lstk entries, not
  only their contents, and s3 cp/mv/sync refuse an s3:// argument with a
  .git or .lstk component (a single object takes its key's name).
- APFS folds ſ (U+017F) to s and the Kelvin sign to k, so .lſtk was
  .lstk. The path check compares folded names, and the filters include
  those letters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review round 11 (no blockers):

- `signup` is new in AWS CLI 2.41 and opens a browser like `login`; it
  joins the deny list.
- The CLI anchors the .git/.lstk filters at the local root, which lies in
  the working directory, so a `[`, `*` or `?` in the working directory's
  path defused them. s3 cp, mv and sync are refused there, with a hint to
  set LOCALSTACK_AWS_WORKDIR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
In the image, LOCALSTACK_HOSTNAME is host.docker.internal, and the AWS CLI
used it as its endpoint, so `s3 presign` returned
http://host.docker.internal:<port>/..., which does not resolve on the
user's machine. On main, awslocal signed for LOCALSTACK_HOST instead.

The CLI now always addresses a LocalStack on this machine as
localhost.localstack.cloud:<port> and signs for it. The egress guard,
the CLI's proxy for every request, connects those requests (and those for
its subdomains, which no --add-host entry could cover) to
host.docker.internal in the image and to 127.0.0.1 on a host. A
LocalStack on another machine keeps its own name.

Tests: lstkAwsRoute unit tests, and validate-image.mjs presigns a URL
through the image and fetches it from the host.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The path rule skipped every value that looked like a URL, and C://Users/x
matched, though the AWS CLI on Windows reads it as C:\Users\x. A URL now
needs a scheme of two or more lower-case letters: one letter is a drive,
and the CLI knows s3:// in lower case only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@joe4dev
joe4dev force-pushed the devx-1330-mcp-server-run-aws-cli-commands-with-the-official branch from 0fc287c to 79fb743 Compare November 23, 2026 11:11
joe4dev and others added 2 commits November 23, 2026 12:44
…is none

`::1`, `a@b` or `evil.com:81` as the host, or `abc` as the port, failed
every command with a bare "Invalid URL" or silently named another host.
The host must now be a DNS name or IPv4 address and the port a number from
1 to 65535; the host is compared in lower case, so LOCALHOST is local too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ck in tests only when allowed

get-game-session-log is the only AWS CLI command that fetches a URL from a
server's response, with urlopen, which opens file:// URLs too: a returned
file:// URL would copy a local file into the working directory.

The live test for the AWS client stopped and started LocalStack, so run
locally it restarted the developer's instance with the server's settings.
It now does so only with MCP_TEST_RESTART_LOCALSTACK=1, which CI sets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@joe4dev

joe4dev commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

FYI: Related open question in AGENTS.md https://github.com/localstack/localstack-mcp-server/pull/136/changes#diff-a54ff182c7e8acf56acfd6e4b9c3ff41e2c41a31c9b211b2deb9df75d9a478f9R323

  • How the server passes its target to lstk (rule 1). The proposal: pass it as LSTK_ENDPOINT_URL, which lstk
    prefers over AWS_ENDPOINT_URL (so a value in the user's environment does not win), to the commands that accept
    an endpoint, and to none of the commands lstk's rejectEndpointURL (cmd/endpoint.go) refuses one for. Today
    the deployer passes AWS_ENDPOINT_URL (src/core/localstack-env.ts). Open:
    • Is this the intended contract?
    • If the server runs a command lstk refuses an endpoint for, must it also remove the endpoint variables it
      inherited from the user's shell?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant